<template>
  <div v-loading="loading">
    <el-form
      :model="detail"
      label-width="80px"
      ref="formRef"
      :rules="rules"
      style="max-width: 500px"
    >
      <el-form-item prop="ClassName" label="班级名">
        <el-input v-model="detail.ClassName" clearable />
      </el-form-item>
      <el-form-item prop="DseGrade" label="年级">
        <el-select v-model="detail.DseGrade" clearable placeholder="Select">
          <el-option
            v-for="item in enum2Collection(DseGradeEnum)"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div v-loading="loading" class="my_opt_btn_pannel">
      <div style="text-align: left">
        <el-button @click="router.back()">返回</el-button>
      </div>
      <div style="text-align: right; padding-right: 20px">
        <el-button v-if="optUser.isAdm" type="primary" @click="submit">保存</el-button>
        <el-button v-if="optUser.isAdm" @click="setInfo()">重置</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { getDseClass, saveDseClass } from '@/api/dseclass'
import { useUserStore } from '@/stores/user'
import type { DseClassModel } from '@/type/DseClass'
import { DseGradeEnum } from '@/type/DseClass'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { enum2Collection } from '@/utils/stringUtils'
import { DeconstructionKvModel } from '@/utils/objUtils'
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const detail = ref<DseClassModel>({})
const optUser = useUserStore()
console.log(enum2Collection(DseGradeEnum))
let detail_copy = ''
onMounted(async () => {
  if (route.query.pk) {
    loading.value = true
    try {
      const c = (await getDseClass(route.query.pk.toString())).Data[0]!
      DeconstructionKvModel(c)
      detail.value = c
    } finally {
      loading.value = false
    }
  }
  detail_copy = JSON.stringify(detail.value)
})

const setInfo = () => {
  detail.value = JSON.parse(detail_copy)
}
const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  ClassName: [{ required: true, message: '请输入班级名', trigger: 'blur' }],
  DseGrade: [{ required: true, message: '请输入年级', trigger: 'blur' }],
})
const submit = async () => {
  loading.value = true
  try {
    await formRef.value?.validate()
    const r = await saveDseClass(detail.value)
    const rd = r.Data[0]!
    DeconstructionKvModel(rd)
    detail_copy = JSON.stringify(rd)
    detail.value = rd
    ElMessage.success('操作成功')
  } finally {
    loading.value = false
  }
}
</script>
